package com.weatherstation;

import com.weatherstation.entity.SensorData;
import com.weatherstation.mapper.SensorDataMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * 数据初始化器
 * 在应用启动时添加测试数据
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class DataInitializer implements CommandLineRunner {
    
    private final SensorDataMapper sensorDataMapper;
    private final Random random = new Random();
    
    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化测试数据...");
        
        // 检查是否已有数据
        if (sensorDataMapper.selectCount(null) > 0) {
            log.info("数据库中已有数据，跳过初始化");
            return;
        }
        
        // 生成过去24小时的测试数据
        LocalDateTime now = LocalDateTime.now();
        for (int i = 23; i >= 0; i--) {
            LocalDateTime time = now.minusHours(i);
            
            SensorData data = new SensorData();
            data.setTemperature(generateTemperature(time));
            data.setHumidity(generateHumidity(time));
            data.setPressure(generatePressure(time));
            data.setLightIntensity(generateLightIntensity(time));
            data.setCreatedAt(time);
            data.setUpdatedAt(time);
            
            sensorDataMapper.insert(data);
        }
        
        log.info("测试数据初始化完成，共生成 {} 条记录", sensorDataMapper.selectCount(null));
    }
    
    /**
     * 生成温度数据（模拟昼夜变化）
     */
    private BigDecimal generateTemperature(LocalDateTime time) {
        int hour = time.getHour();
        // 模拟昼夜温度变化：凌晨最低，下午最高
        double baseTemp = 20.0;
        double variation = Math.sin((hour - 6) * Math.PI / 12) * 8; // 昼夜温差16度
        double noise = (random.nextDouble() - 0.5) * 2; // 随机噪声
        return BigDecimal.valueOf(baseTemp + variation + noise).setScale(1, BigDecimal.ROUND_HALF_UP);
    }
    
    /**
     * 生成湿度数据
     */
    private BigDecimal generateHumidity(LocalDateTime time) {
        int hour = time.getHour();
        // 模拟湿度变化：夜间湿度高，白天湿度低
        double baseHumidity = 60.0;
        double variation = Math.cos((hour - 6) * Math.PI / 12) * 15; // 湿度变化30%
        double noise = (random.nextDouble() - 0.5) * 5; // 随机噪声
        double humidity = baseHumidity + variation + noise;
        // 确保湿度在合理范围内
        humidity = Math.max(30, Math.min(90, humidity));
        return BigDecimal.valueOf(humidity).setScale(1, BigDecimal.ROUND_HALF_UP);
    }
    
    /**
     * 生成气压数据
     */
    private BigDecimal generatePressure(LocalDateTime time) {
        // 气压相对稳定，只有小幅波动
        double basePressure = 101325.0; // 标准大气压
        double variation = (random.nextDouble() - 0.5) * 2000; // 随机波动
        return BigDecimal.valueOf(basePressure + variation).setScale(0, BigDecimal.ROUND_HALF_UP);
    }
    
    /**
     * 生成光照强度数据
     */
    private Integer generateLightIntensity(LocalDateTime time) {
        int hour = time.getHour();
        // 模拟光照强度：夜间为0，中午最高
        if (hour < 6 || hour > 18) {
            // 夜间
            return random.nextInt(50); // 0-50 lux
        } else {
            // 白天
            double maxLight = 1000.0;
            double factor = Math.sin((hour - 6) * Math.PI / 12); // 6点到18点
            double light = maxLight * factor * factor; // 平方关系，中午最强
            double noise = (random.nextDouble() - 0.5) * 100; // 随机噪声
            return Math.max(0, (int) (light + noise));
        }
    }
} 